// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const { merchantId, merchantInfo } = event;
  const { OPENID } = cloud.getWXContext();

  try {
    // 查询商家信息
    const merchantResult = await db
      .collection("merchants")
      .doc(merchantId)
      .get();
    const merchant = merchantResult.data;

    // 验证商家权限
    if (merchant._openid !== OPENID) {
      return {
        code: -1,
        msg: "无权限操作此商家信息",
      };
    }

    // 更新商家信息
    const result = await db
      .collection("merchants")
      .doc(merchantId)
      .update({
        data: {
          ...merchantInfo,
          updateTime: db.serverDate(),
        },
      });

    return {
      code: 0,
      msg: "更新成功",
      data: result,
    };
  } catch (err) {
    console.error(err);
    return {
      code: -1,
      msg: "更新失败",
      error: err,
    };
  }
};
